package org.micode.common.file;

import org.micode.common.codec.SnowflakeCodec;
import org.micode.common.utils.StringExtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class TargetPathHelper {

    private SnowflakeCodec snowflakeCodec;

    private String base;
    private String filename;
    private Long fileId;
    private String newFilename;
    private Path targetPath;
    private UploadFileTypeEnum fileType;
    private String bizType;
    private String langType;

    /**
     * 文件扩展名
     */
    private String extName;

    /**
     * 不包括扩展名的文件名
     */
    private String realName;

    /**
     * 不包括扩展名的文件名
     */
    private String newRealName;

    /**
     * 当前客户
     */
    private Long customerId;

    public TargetPathHelper(SnowflakeCodec snowflakeCodec,
                            String base,
                            String filename,
                            String bizType,
                            String langType,
                            UploadFileTypeEnum fileType,
                            Long customerId) {
        this.snowflakeCodec = snowflakeCodec;
        this.base = base;
        this.filename = filename;
        this.fileType = fileType;
        this.bizType = bizType;
        this.langType= langType;
        this.extName = readExtName(filename);
        this.realName = readRealName(filename);
        this.customerId = customerId;
    }

    private String readExtName(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    private String readRealName(String filename) {
        return filename.substring(0, filename.lastIndexOf("."));
    }

    public Long getFileId() {
        return fileId;
    }

    public String getNewFilename() {
        return newFilename;
    }

    public String getNewRealName() {
        return newRealName;
    }

    public String getNewRealPath() {
        return readRealName(targetPath.toString());
    }

    public Path getTargetPath() {
        return targetPath;
    }

    public TargetPathHelper invoke() throws IOException {
        // 上传目录:  {base}/{customerId}/{bizType}/{langType}/
        Path path = Paths.get(getTargetPath(base, customerId, bizType, langType));

        if (!Files.exists(path)){
            Files.createDirectories(path);
        }

        // 文件名称加上一个snowID，以确保唯一
        fileId = snowflakeCodec.nextId();
//        newRealName = realName + "-" + Long.toString(fileId);
        newRealName = Long.toString(fileId);
        newFilename = newRealName + "." + extName;

        // 如果存在同名文件，先删除
        targetPath = Paths.get(path.toString() + "/" + newFilename);
        if (Files.exists(targetPath)){
            boolean b = Files.deleteIfExists(targetPath);
            log.info("the file name already exists: " + newFilename + "，remove it? " + b);
        }
        return this;
    }

    private String getFileTypeName() {
        return null == fileType
                ? UploadFileTypeEnum.OTHER.getName()
                : fileType.getName();
    }

    public static String getTargetPath(String base, Long customerId, String bizType, String langType) {
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.appendIfMissing(base, "/"))
                .append(null == customerId ? "default" : customerId.toString()).append("/")
                .append(bizType).append("/");
        if (!StringExtUtils.isAnyEmpty(langType) && !"None".equals(langType)) {
            sb.append(langType).append("/");
        }
        return sb.toString();
    }

    public static String getTargetPath(String base, Long customerId, Long ivrId, String langType) {
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.appendIfMissing(base, "/"))
                .append(null == customerId ? "default" : customerId.toString()).append("/")
                .append(ivrId).append("/");
        if (!StringExtUtils.isAnyEmpty(langType) && !"None".equals(langType)) {
            sb.append(langType).append("/");
        }
        return sb.toString();
    }

}
